import React, { useEffect, useState } from 'react';
import {
  NavBar,
  List,
  Card,
  Tag,
  Empty,
  PullToRefresh,
  InfiniteScroll,
  SearchBar,
  Toast,
} from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import styles from './index.module.css';
import request from '../../axios';

// 设备状态枚举
const DEVICE_STATUS = {
  ONLINE: { value: 1, label: '在线', color: 'success' },
  OFFLINE: { value: 0, label: '离线', color: 'default' },
  MAINTENANCE: { value: 2, label: '维护中', color: 'warning' },
  ERROR: { value: 3, label: '故障', color: 'danger' },
} as const;

interface DeviceItem {
  id: string;
  deviceId: string;
  status: number;
  firmwareVersion: string;
  storeName: string;
  lastOnlineTime: string;
  createTime?: string;
}

const Device: React.FC = () => {
  const navigate = useNavigate();
  const [deviceList, setDeviceList] = useState<DeviceItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [pageNo, setPageNo] = useState(1);
  const [searchText, setSearchText] = useState('');

  // 获取设备列表
  const getDeviceList = async (page: number = 1, search: string = '', isRefresh: boolean = false) => {
    try {
      setLoading(true);
      const { data } = await request.get('/device/list', {
        pageNo: page,
        pageSize: 10,
        search: search.trim() || undefined,
      });

      if (data && data.records) {
        if (isRefresh || page === 1) {
          setDeviceList(data.records);
        } else {
          setDeviceList(prev => [...prev, ...data.records]);
        }
        setHasMore(data.records.length >= 10);
        setPageNo(page);
      }
    } catch (error) {
      Toast.show('获取设备列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 下拉刷新
  const onRefresh = async () => {
    await getDeviceList(1, searchText, true);
  };

  // 加载更多
  const loadMore = async () => {
    if (!hasMore) return;
    await getDeviceList(pageNo + 1, searchText);
  };

  // 搜索
  const onSearch = (value: string) => {
    setSearchText(value);
    setPageNo(1);
    getDeviceList(1, value, true);
  };

  // 获取设备状态标签
  const getStatusTag = (status: number) => {
    const statusInfo = Object.values(DEVICE_STATUS).find(item => item.value === status) || DEVICE_STATUS.OFFLINE;
    return (
      <Tag color={statusInfo.color} className={styles.statusTag}>
        {statusInfo.label}
      </Tag>
    );
  };

  // 格式化时间
  const formatTime = (timeString: string) => {
    if (!timeString) return '未知';
    const date = new Date(timeString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    return date.toLocaleDateString('zh-CN');
  };

  useEffect(() => {
    getDeviceList();
  }, []);

  return (
    <div className={styles.container}>
      <NavBar
        onBack={() => navigate('/mine')}
        className={styles.navbar}
      >
        设备管理
      </NavBar>

      {/* 搜索栏 */}
      <div className={styles.searchContainer}>
        <SearchBar
          placeholder="搜索设备ID或门店名称"
          onSearch={onSearch}
          onClear={() => onSearch('')}
        />
      </div>

      {/* 设备列表 */}
      <div className={styles.listContainer}>
        <PullToRefresh onRefresh={onRefresh}>
          {deviceList.length > 0 ? (
            <List>
              {deviceList.map((device) => (
                <List.Item key={device.id} className={styles.listItem}>
                  <Card className={styles.deviceCard}>
                    <div className={styles.cardHeader}>
                      <div className={styles.deviceInfo}>
                        <span className={styles.deviceId}>设备: {device.deviceId}</span>
                        {getStatusTag(device.status)}
                      </div>
                    </div>
                    
                    <div className={styles.cardContent}>
                      <div className={styles.infoRow}>
                        <span className={styles.label}>固件版本:</span>
                        <span className={styles.value}>{device.firmwareVersion || '未知'}</span>
                      </div>
                      
                      <div className={styles.infoRow}>
                        <span className={styles.label}>绑定门店:</span>
                        <span className={styles.value}>{device.storeName || '未绑定'}</span>
                      </div>
                      
                      <div className={styles.infoRow}>
                        <span className={styles.label}>最后上线:</span>
                        <span className={styles.value}>{formatTime(device.lastOnlineTime)}</span>
                      </div>
                    </div>
                  </Card>
                </List.Item>
              ))}
            </List>
          ) : (
            !loading && (
              <Empty
                description="暂无设备数据"
                imageStyle={{ width: 128, height: 128 }}
              />
            )
          )}
          
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
            {hasMore ? (
              <div className={styles.loadingText}>加载中...</div>
            ) : (
              deviceList.length > 0 && (
                <div className={styles.noMoreText}>没有更多数据了</div>
              )
            )}
          </InfiniteScroll>
        </PullToRefresh>
      </div>
    </div>
  );
};

export default Device;